# needs these libraries
library(distory)
library(phangorn)
library(data.table) #enable library with fread command
library(TreeTools)
library(Quartet)
# set working directory ctrl-shift-h according to dataset
# setwd("C:/ ...")

# script to extract strict consensus files
# output of this loop is file "treesstrict.txt" which has strict consensus of TNT treefiles corresponding to each subject & template (as extracted from filenames)
prefix<-"rand" #change pattern to suit names of tnt output files
treesStrict<-"treesStrict.txt" #define variable for later writing
suffix<-".out" #change pattern to suit names of tnt output files
# script to extract TNT trees from text files in working directory; make "recursive=T" to look inside subfolders
# Double check that no other filenames sneak into "z", e.g., by typing "z" and examining that all contents correspond to desired TNT batchfile output
z<-list.files(path=".",pattern=suffix,recursive=F) 
for (i in 1:length(z) ){ #define for-loop to go through each filename in z
  filename<-gsub(suffix,"",z[i])
  filename<-gsub(prefix,"",filename)
  template<-gsub(".*?\\_","",filename)
  subject<-gsub("\\_.*","",filename)
  lineStrict<-length(count.fields(file=z[i],blank.lines.skip = F))-3 #TNT writes strict consensus 4 lines from the end, read by count.fields as 5, so length(count.fields[file])-3 has last newick topology written to TNT outfile
  strict <- read.table(z[i],skip = lineStrict, nrows=1, sep=";", header=F) #reads into variable tree one row of text from file z[i] starting at lineStrict 
  write(paste(subject,"=",template,"=",strict$V1,";",sep=" "),file=treesStrict,append=T)
} #close for-loop

#read "treesstrict.txt" and convert into data frame "randTrees"
randTrees<-read.table("treesstrict.txt",sep="=",col.names = c("subject","template","topo")) #write each line as an observation with columns separated by "=" 
#read column w/ topologies and write each line to a new file
write(paste(randTrees$topo), file="randTrees.nwk") 


# calculate tree dists and clades in common using prop.clades; equivalent to mesquite shared partitions + 1
# the following loop writes the file "RF_shared.csv", a spreadsheet with proportion resolved, RF, cRF or RF scaled by resolution, and # shared splits between each testtree and reftree 
reftree<-read.tree("wellcorr.nwk") # pick your reference tree (e.g., "wellcorr.nwk")
testtrees<-read.tree("randTrees.nwk") # read topology from testtrees.txt column V2, saved previously as "randTrees.nwk"
#the previous line reads testtrees from "randTrees.nwk". This could probably be done more efficiently from dataframe randTrees$topo but I've not yet gotten this to work. Please feel free to have a try. 
outfile <- "RF_shared.csv" # define file for writing in loop below
write(paste("subject","template","resolved","randS.RF","randS.cRF","randS.shared","randS.QD",sep = ","),  file = outfile, append = T) #write column labels for loop below
for (i in 1:length(testtrees) ){
  refTaxa <- reftree$tip.label
  tree <- testtrees[[i]]
  thisTaxa <- tree$tip.label
  tree <- drop.tip(tree, setdiff(thisTaxa, refTaxa))
  reftreeTemp <- drop.tip(reftree, setdiff(refTaxa, thisTaxa)) # this prunes tips in reftree to those in common between reftree and testtree[i]
  pbif<-NSplits(NTip(tree)) # possible bifurcating, fully resolved unrooted tree has ntax - 1 nodes as written by TNT
  bif<-NSplits(tree) #"bif" = actual bifurcating, number of actually resolved nodes in tree[i]
  res<-bif/pbif #resolved/total possible resolved = proportion out of 1 resolved
  randS.RF <- TreeDist::RobinsonFoulds(tree, reftreeTemp)
  randS.cRF<-randS.RF/res
  randS.shared<-sum(as.Splits(tree) %in% as.Splits(reftreeTemp))
  statuses <- QuartetStatus(tree, reftreeTemp) #suggested by Martin Smith
  randS.QD<-QuartetDivergence(statuses,similarity = T)
  # next line to write output. ensure to change name before "$" to relevant vector with replicate & # character info 
  write(paste(randTrees$subject[i],randTrees$template[i],res,randS.RF,randS.cRF,randS.shared,randS.QD,sep = ","),  file = outfile, append = T)
}

#here you can read back the csv file into dataframe "RFS", then get averages etc. for subjects per template, etc.
#note in my example "sampleComb.tnt" every subject-template combination gives the same result (in part because wellcor.nwk is an unrooted tree with only 4 taxa, so there's not much there for comparison)
#also please double check for errors by directly comparing phylogeny program output with the various artex files read/written here
RFS<-read.csv(file.choose("RF_shared.csv"),header = T) #this should be "RF_shared.csv" file with stats for every subject-template combination
dt<-data.table(RFS)
randS.shared<-dt[, list(randS.shared.mean=sapply(.SD,mean), randS.shared.median=sapply(.SD, median), randS.shared.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
           by="template", .SDcols=c("randS.shared")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)
randS.cRF<-dt[, list(randS.cRF.mean=sapply(.SD,mean), randS.cRF.median=sapply(.SD, median), randS.cRF.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
        by="template", .SDcols=c("randS.cRF")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)
randS.QD<-dt[, list(randS.QD.mean=sapply(.SD,mean), randS.QD.median=sapply(.SD, median), randS.QD.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
           by="template", .SDcols=c("randS.QD")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)

#load & add metadata
meta<-read.csv("rtxMeta.csv",header = T)
#make sure that templates correspond exactly in row order before combining columns 
randS.shared<-randS.shared[order(randS.shared$template),]
randS.cRF<-randS.cRF[order(randS.cRF$template),]
randS.QD<-randS.QD[order(randS.QD$template),]
#combine columns
rtx<-cbind(meta,randS.shared,randS.cRF,randS.QD)
#check that template columns in rtx correspond and then delete extraneous column
rtx[,12]<-NULL #REMEMBER to check if the column you want to delete is "12"
rtx[,8]<-NULL #REMEMBER to check if the column you want to delete is "8"
rtx[,14]<-NULL
write.csv(rtx,file = "rtxAimeGlires.csv",row.names = F)

#display results, %complete on Xaxis, shared.mean on Yaxis, errorbars = one stdev
library(ggplot2)
ggplot(data=rtx)+
  geom_linerange(aes(x=complete,ymin=(shared.mean-shared.stdev),ymax=(shared.mean+shared.stdev)))+
  geom_point(aes(x=complete,y=shared.mean))+
  #next two lines add cRF in red which happen to have similar Yaxis scale
  geom_linerange(aes(x=complete,ymin=(cRF.mean-cRF.stdev),ymax=(cRF.mean+cRF.stdev),color="red",alpha=0.5))+
  geom_point(aes(x=complete,y=cRF.mean,color="red",alpha=0.5))
#ggplot is very flexible and you should consult documentation to get correct axis labels, tweak colors, alpha levels, etc.


